package com.jason.fingerprint.logic;

/**
 * @Title: ValidateFingerprintSyncLogic.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月25日 上午12:16:14
 * @Version: V1.0
 */

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.kymjs.aframe.utils.StringUtils;

import android.fpi.MtRfid;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android_serialport_api.FingerprintManager;
import android_serialport_api.FingerprintReader;
import android_serialport_api.FingerprintReader.OnGenCharExListener;
import android_serialport_api.FingerprintReader.OnGetImageExListener;
import android_serialport_api.FingerprintReader.OnRegModelListener;
import android_serialport_api.FingerprintReader.OnSearchListener;
import android_serialport_api.FingerprintReader.OnUpCharListener;
import android_serialport_api.FingerprintReader.OnUpImageExListener;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.utils.CodecUtils;

/**
 * @ClassName: ValidateFingerprintSyncLogic
 * @Description: 验证指纹
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月25日 上午12:16:14
 */
public class ValidateFingerprintSyncLogic extends Logic {

	private static final String TAG = "ValidateFingerprintSyncLogic";
	public static final String SIGNIN_TYPE = "finger_type";
	private static final int SIGNIN_TYPE_FINGER = 0;
	private static final int SIGNIN_TYPE_PLATFORM = 1;
	private static final int SIGNIN_TYPE_CARD= 2;

	private FingerprintReader mValidateFingerprint;
	private Handler mHandler;
	private boolean mIsCallBack = false;// 是否有回调，此需要Handle
	private boolean mIsShowImage = true;// 是否显示图像
	private Message mMessage;
	private int mCount;
	private List<FingerPrintBean> mFingerPrintBeans;
	private boolean mIsManager = false;//判断是否是管理员,默认false--矫正人员，
	private boolean mIsDestory = false;
	
	//打开
	private Timer xTimer=null; 
    private TimerTask xTask=null; 
    private Handler xHandler;

	public ValidateFingerprintSyncLogic() {

	}

	public ValidateFingerprintSyncLogic(AppContext appContext, Handler handler) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
	}

	public ValidateFingerprintSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
		initListener();
	}

	public ValidateFingerprintSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack, boolean isShowImage) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
		this.mIsShowImage = isShowImage;
		initListener();
	}
	
	public ValidateFingerprintSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack, boolean isShowImage,boolean isManager) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
		this.mIsShowImage = isShowImage;
		this.mIsManager = isManager;
		initListener();
	}
	
	private void initCard(){
		xTimer = new Timer(); 
		xHandler = new Handler() { 
			@Override 
	        public void handleMessage(Message msg) { 
				
				int[] sn=new int[8];
				if(MtRfid.getInstance().RfidGetSn(sn)==0){
					xTimerStop();
					int[] buffer=new int[4096];
					String cardNO = CodecUtils.conver8ByteTo10String(sn);
					Log.i(TAG, "---->initCard cardNO :" + cardNO);
					int pageId = getPageIdFormCardNO(cardNO);
					Log.i(TAG, "---->initCard pageId :" + pageId);
					if (pageId == -1) {
						mMessage.what = UIHelper.FINGERPRINT_SEARCH_FAIL;
						send();
					}else {
						mMessage.what = UIHelper.FINGERPRINT_SEARCH_SUCCESS;
						mMessage.arg1 = pageId;
						mMessage.arg2 = SIGNIN_TYPE_CARD;
						send();
					}
					
				}
	            super.handleMessage(msg); 
	        }
	    };
	    xTask = new TimerTask() { 
	        @Override 
	        public void run() {
	        	if (!mIsDestory && !mIsManager) {
	        		Message message = new Message(); 
	        		message.what = 1; 
	        		xHandler.sendMessage(message); 
				}
	        } 
	    }; 
	}

	@Override
	public void execute() {
		//TODO 暂时去掉刷卡 !mIsManager
		if (!mIsManager) {
			initCard();
			xTimerStart();
		}
		validateFingerprintSync();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jason.fingerprint.logic.Logic#send()
	 */
	@Override
	public void send() {
		if (mIsCallBack) {
			mHandler.sendMessage(mMessage);
			mMessage = new Message();
		}

	}
	
	public void destory(){
		if (mMessage != null) {
			mIsDestory = true;
			xTimerStop();
			mMessage = new Message();
			mMessage.what = 100000;
			mHandler.sendMessage(mMessage);
		}
	}

	// 初始化监听
	private void initListener() {
		mValidateFingerprint = FingerprintManager.getInstance().getNewAsyncFingerprint();
		mCount = 1;
		// 判断返回时图片还是文字
		mValidateFingerprint
				.setOnGetImageExListener(new OnGetImageExListener() {
					@Override
					public void onGetImageExSuccess() {
						Log.i(TAG,
								"---->setOnGetImageExListener onGetImageExSuccess 001");
						// cancleProgressDialog();
						if (mIsShowImage) {
							mValidateFingerprint.PS_UpImageEx();//
							// showProgressDialog("正在处理...");
							Log.i(TAG,
									"---->setOnGetImageExListener onGetImageExSuccess 008");
						} else {
							mValidateFingerprint.PS_GenCharEx(mCount);
							Log.i(TAG,
									"---->setOnGetImageExListener onGetImageExSuccess 009");
						}
					}

					@Override
					public void onGetImageExFail() {
						Log.i(TAG,
								"---->setOnGetImageExListener onGetImageExFail 002");
						if (!mIsDestory) {
							mValidateFingerprint.PS_GetImageEx();
						}
					}
				});

		// 图片---返回的图片结果
		mValidateFingerprint.setOnUpImageExListener(new OnUpImageExListener() {
			@Override
			public void onUpImageExSuccess(byte[] data) {
				Log.i(TAG,
						"---->setOnGetImageExListener onUpImageExSuccess 010");
				Log.i(TAG, "---->setOnUpImageExListener up image data.length="
						+ data.length);
				mValidateFingerprint.PS_GenCharEx(mCount);
				mMessage.what = UIHelper.FINGERPRINT_UPIMAGE_SUCCESS;
				Bundle bundle = new Bundle();
				bundle.putByteArray(UIHelper.FINGERPRINT_SOURCE, data);
				mMessage.setData(bundle);
				send();
			}

			@Override
			public void onUpImageExFail() {
				Log.i(TAG, "---->setOnGetImageExListener onUpImageExFail 011");
				mMessage.what = UIHelper.FINGERPRINT_UPIMAGE_FAIL;
				send();
			}
		});

		// 文字---监听文字返回结果
		mValidateFingerprint.setOnGenCharExListener(new OnGenCharExListener() {
			@Override
			public void onGenCharExSuccess(int bufferId) {
				Log.i(TAG,
						"---->setOnGenCharExListener onGenCharExSuccess 012 bufferId:"
								+ bufferId);
				if (bufferId == 1) {
					mValidateFingerprint.PS_GetImageEx();
					mCount++;
					mMessage.what = UIHelper.FINGERPRINT_AGAIN;
					send();
				} else if (bufferId == 2) {
					//mValidateFingerprint.PS_RegModel();
					mValidateFingerprint.PS_Search(1, 0, 1000);
				}
			}

			@Override
			public void onGenCharExFail() {
				Log.i(TAG, "---->setOnGenCharExListener onGenCharExFail 013");
				// cancleProgressDialog();
				// ToastUtil.showToast(FingerprintActivity.this,"生成特征值失败！");
				//mMessage.what = UIHelper.FINGERPRINT_GENCHAR_FAIL;
				//send();
				xTimerStop();
				mValidateFingerprint.PS_Search(1, 0, 1000);
			}
		});

		// 文字---文字模板合成
		/*mValidateFingerprint.setOnRegModelListener(new OnRegModelListener() {

			@Override
			public void onRegModelSuccess() {
				Log.i(TAG, "---->setOnGenCharExListener onGenCharExSuccess 014");
				// cancleProgressDialog();
				mValidateFingerprint.PS_UpChar();
				// ToastUtil.showToast(FingerprintActivity.this, "合成模板成功！");
			}

			@Override
			public void onRegModelFail() {
				Log.i(TAG, "---->setOnGenCharExListener onGenCharExSuccess 015");
				// cancleProgressDialog();
				// ToastUtil.showToast(FingerprintActivity.this, "合成模板失败！");
				mMessage.what = UIHelper.FINGERPRINT_REGMODE_FAIL;
				send();
			}
		});

		// 文字---返回文字结果集
		mValidateFingerprint.setOnUpCharListener(new OnUpCharListener() {
			@Override
			public void onUpCharSuccess(byte[] model) {
				Log.i(TAG,
						"---->setOnGenCharExListener onGenCharExSuccess 016 lenth:"
								+ model.length);
				mValidateFingerprint.PS_Search(1, 0, 1000);
			}

			@Override
			public void onUpCharFail() {
				Log.i(TAG, "---->setOnGenCharExListener onGenCharExSuccess 017");
				// cancleProgressDialog();
				// ToastUtil.showToast(FingerprintActivity.this, "注册失败！");
				mMessage.what = UIHelper.FINGERPRINT_UPCHAR_FAIL;
				send();
			}
		});*/

		// 搜索指纹
		mValidateFingerprint.setOnSearchListener(new OnSearchListener() {
			@Override
			public void onSearchSuccess(int pageId, int matchScore) {
				// ToastUtil.showToast(FingerprintActivity.this, "搜索成功！");
				Log.i(TAG, "pageId=" + pageId + "    matchScore="
						+ matchScore);
				xTimerStop();
				mMessage.what = UIHelper.FINGERPRINT_SEARCH_SUCCESS;
				mMessage.arg1 = pageId;
				mMessage.arg2 = SIGNIN_TYPE_FINGER;
				send();
				Log.i(TAG,
						"---->setOnGenCharExListener setOnSearchListener " + 22);
			}

			@Override
			public void onSearchFail() {
				// ToastUtil.showToast(FingerprintActivity.this, "搜索失败！");
				xTimerStop();
				mMessage.what = UIHelper.FINGERPRINT_SEARCH_FAIL;
				send();
				Log.i(TAG, "---->setOnGenCharExListener onSearchFail " + 23);
			}
		});
	}

	// 录入指纹
	private synchronized void validateFingerprintSync() {
		if (mValidateFingerprint != null) {
			mValidateFingerprint.PS_GetImageEx();
		}
	}
	
	//开始打卡
	public void xTimerStart() {
		xTimer.schedule(xTask, 1000, 500);
	}
	
	//关闭
	public void xTimerStop() {
		if (xTimer!=null && xTask != null ) {  
			xTimer.cancel();  
			xTimer = null;  
			xTask.cancel();
			xTask=null;
		}
	}
	
	//根据监管卡号获取当前的pageId
	private int getPageIdFormCardNO(String cardNo){
		if (StringUtils.isEmpty(cardNo)) {
			return -1;
		}
		try {
			mFingerPrintBeans = mKjdb.findAllByWhere(FingerPrintBean.class, " type = 1 and cardNo = '" + cardNo + "'");
		} catch (Exception e) {
			return -1;
		}
		if (mFingerPrintBeans != null && !mFingerPrintBeans.isEmpty()) {
			FingerPrintBean bean = mFingerPrintBeans.get(0);
			if (bean != null) {
				return bean.getId();
			}
		}
		return -1;
	}

}
